package com.malou.client.ventas.cliente;

import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.google.gwt.core.client.GWT;
import com.malou.client.MalouConstants;
import com.malou.client.util.Utilities;

public class ClienteDialog extends Dialog {

	protected HiddenField<String> id;
	protected TextField<String> apellidos;
	protected TextField<String> nombres;
	protected TextField<String> ruc;
	protected TextField<String> telefono;
	protected TextField<String> celular;
	protected TextField<String> email;
	protected TextField<String> razonsocial;
	protected TextField<String> dni;

	protected Button guardar;
	protected Button cancelar;
	protected Status status;
	private FormBinding formBindings;

	private FormPanel panel;
	private MalouConstants constants = GWT.create(MalouConstants.class);

	public ClienteDialog() {
		super();
		setModal(true);
		setSize(450, 300);
		setResizable(false);
		setButtons("");

		panel = new FormPanel();
		panel.setBorders(false);
		panel.setBodyBorder(false);
		panel.setPadding(5);
		panel.setHeaderVisible(false);
		panel.setLabelWidth(110);

		formBindings = new FormBinding(panel, false);
		addFields();
		setFocusWidget(nombres);
		Component comp[] = { nombres, apellidos, dni, razonsocial, ruc,
				telefono, celular, email, guardar };
		Utilities.Enter(comp);

	}

	@Override
	protected void createButtons() {
		super.createButtons();

		if (constants == null) {
			constants = GWT.create(MalouConstants.class);
		}

		status = new Status();
		status.setBusy(constants.guardando());
		status.hide();
		status.setAutoWidth(true);
		getButtonBar().add(status);

		getButtonBar().add(new FillToolItem());

		
		 
	    cancelar = new Button(constants.cancelar(),
				IconHelper.createPath("images/icons/cancel.png"));
		cancelar.setSize(70, 25);
		cancelar.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				ClienteDialog.this.hide();
			}

		});

		guardar = new Button(constants.guardar(),
				IconHelper.createPath("images/icons/save_all.png"));
		guardar.setSize(70, 25);

		guardar.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				guardar();
			}
		});

		addButton(guardar);
		addButton(cancelar);

	}

	protected boolean validate() {
		boolean ape = apellidos.isValid();
		boolean nom = nombres.isValid();

		boolean ru = ruc.isValid();
		boolean tel = telefono.isValid();
		boolean cel = celular.isValid();
		boolean em = email.isValid();
		boolean rz = razonsocial.isValid();
		boolean dn = dni.isValid();
		return ape && nom && ru && tel && cel && em && rz && dn;
	}

	public void reset() {
		setIconStyle("icon-new");
		setHeading(constants.clienteNuevoCliente());

		id.clear();
		apellidos.clear();
		nombres.clear();

		ruc.clear();
		telefono.clear();
		celular.clear();
		email.clear();
		razonsocial.clear();
		dni.clear();
		status.hide();
		
	}

	public void setStore(ListStore<BeanModel> store) {

		formBindings.addFieldBinding(new FieldBinding(id, "id"));
		formBindings.addFieldBinding(new FieldBinding(dni, "dni"));
		formBindings.addFieldBinding(new FieldBinding(apellidos, "apellidos"));
		formBindings.addFieldBinding(new FieldBinding(nombres, "nombres"));
		formBindings.addFieldBinding(new FieldBinding(ruc, "ruc"));
		formBindings.addFieldBinding(new FieldBinding(telefono, "telefono"));
		formBindings.addFieldBinding(new FieldBinding(celular, "celular"));
		formBindings.addFieldBinding(new FieldBinding(email, "email"));
		formBindings.addFieldBinding(new FieldBinding(razonsocial,
				"razonsocial"));

		formBindings.setStore(store);
	}

	private void addFields() {

		id = new HiddenField<String>();
		id.setVisible(false);
		panel.add(id);

		nombres = new TextField<String>();
		nombres.setMinLength(3);
		nombres.setFieldLabel(constants.clienteNombres());
		nombres.setAllowBlank(false);

		apellidos = new TextField<String>();
		apellidos.setMinLength(4);
		apellidos.setFieldLabel(constants.clienteApellidos());
		apellidos.setAllowBlank(false);

		ruc = new TextField<String>();
		ruc.setMinLength(3);
		ruc.setFieldLabel(constants.clienteRuc());
		ruc.setAllowBlank(false);
		ruc.setMaxLength(11);
		ruc.setMinLength(11);
		Utilities.setDigitos(ruc, 11);

		telefono = new TextField<String>();
		telefono.setMinLength(3);
		telefono.setFieldLabel(constants.clienteTelefono());
		Utilities.setNumeric(telefono);

		celular = new TextField<String>();
		celular.setMinLength(3);
		celular.setFieldLabel(constants.clienteCelular());
		Utilities.setNumeric(celular);

		email = new TextField<String>();
		email.setMinLength(3);
		email.setFieldLabel(constants.clienteEmail());

		final String emailReg = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
		final String errMsg = constants.emailNoValido();
		email.setValidator(new Validator() {
			public String validate(Field<?> field, String value) {
				if (!value.toUpperCase().matches(emailReg))
					return errMsg;
				return null;
			}
		});

		razonsocial = new TextField<String>();
		razonsocial.setMinLength(3);
		razonsocial.setFieldLabel(constants.clienteRazonSocial());

		dni = new TextField<String>();
		dni.setMinLength(3);
		dni.setFieldLabel(constants.clienteDni());
		dni.setMaxLength(8);
		dni.setMinLength(8);
		Utilities.setDigitos(dni, 8);
		
		panel.add(setLayout(nombres, "95%", 90), new ColumnData(1));
		panel.add(setLayout(apellidos, "95%", 90), new ColumnData(1));
		panel.add(setLayout(dni, "50%", 90), new ColumnData(1));
		panel.add(setLayout(razonsocial, "95%", 90), new ColumnData(1));
		panel.add(setLayout(ruc, "50%", 90), new ColumnData(1));
		panel.add(setLayout(telefono, "50%", 90), new ColumnData(1));
		panel.add(setLayout(celular, "50%", 90), new ColumnData(1));
		panel.add(setLayout(email, "95%", 90), new ColumnData(1));

		add(panel);
	}

	public void beforeEdit() {
		setIconStyle("icon-update");
		setHeading(constants.clienteModificarCliente());

		status.hide();
		
	}

	public void bind(BeanModel selectedModel) {
		formBindings.bind(selectedModel);
	}

	public void unbind() {
		formBindings.unbind();
	}

	private void guardar() {
		if (validate()) {
			status.show();
		
			Cliente cl = new Cliente();
			if (id.getValue() != null)
				cl.setId(Integer.valueOf(id.getValue()));
			cl.setNombres(nombres.getValue());
			cl.setApellidos(apellidos.getValue());
			cl.setRuc(ruc.getValue());
			cl.setTelefono(telefono.getValue());
			cl.setCelular(celular.getValue());
			cl.setEmail(email.getValue());
			cl.setRazonsocial(razonsocial.getValue());
			cl.setDni(dni.getValue());

			Clientes.clienteDialog = ClienteDialog.this;
			Clientes.save(cl);
		}
	}

	private LayoutContainer setLayout(Component comp, String porcentaje,
			Integer withlabel) {
		LayoutContainer layout = new LayoutContainer();
		layout.setStyleAttribute("marginTop", "5px");
		FormLayout fl = new FormLayout(LabelAlign.LEFT);
		fl.setLabelWidth(withlabel);
		layout.setLayout(fl);
		layout.add(comp, new FormData(porcentaje));

		return layout;
	}

}